<!--  -->
<template>
  <div>
    <cus-search style="min-width: 1000px; border: 1px solid #797979; ">
      <cus-search-item>
        <Form :model="form" ref="formValidate" :label-width="100">
          <div style="width: 100%; display: flex; margin-bottom: 20px">
            <FormItem class="mr_48" label="食谱名称" prop="name" :label-width="100" :rules="[
          {
            required: true,
            message: '食谱名称名称不能为空.',
            trigger: 'blur'
          },
          {
            pattern: /^\S+$/,
            message: '食谱名称不能包含空格',
            trigger: 'blur'
          }
        ]">
              <Input v-model="form.name" maxlength="40" style="width: 400px" placeholder="请填写食谱名称" clearable />
            </FormItem>
            <FormItem class="mr_48" label="食谱周次" :label-width="100">
              <el-date-picker v-model="form.dateString" type="week" format="yyyy 第 WW 周" placeholder="选择周"
                @change="weekChange" style="width: 175px" :picker-options="pickerTime">
              </el-date-picker>
              <Tooltip content="默认选中一周日期" placement="top">
                <Icon type="md-information-circle" color="gray" size="26" style="margin-left:20px;color: #33A5FE;" />
              </Tooltip>
            </FormItem>
          </div>
          <div style="width: 100%; display: flex; margin-bottom: 20px">
            <FormItem class="mr_48" label="伙食灶别">
              <Select style="width: 200px" v-model="form.ovenClass" placeholder="全部" label-in-value
                @on-change="changeOvenClass">
                <Option :value="item.id" v-for="(item, index) in ovenClassList" :key="index">{{ item.ovenClass }}
                </Option>
              </Select>
            </FormItem>

            <FormItem class="mr_48" label="伙食类区">
              <Select style="width: 200px" v-model="form.type" @on-change="changeregion" placeholder="全部">
                <Option :value="0">一般地区</Option>
                <Option :value="1">特殊地区</Option>
              </Select>
            </FormItem>
            <FormItem class="mr_48" label="劳动强度">
              <Select style="width: 200px" v-model="form.strength" @on-change="changeStrength" placeholder="全部">
                <Option :value="item.labourId" v-for="(item, index) in labourStrengthList" :key="index">{{ item.strength
                  }}</Option>
              </Select>
            </FormItem>

            <FormItem class="mr_48" label="伙食档口">
              <Select style="width: 200px" v-model="form.stallId" placeholder="全部" label-in-value
                @on-change="changeStall" clearable>
                <Option :value="item.id" v-for="(item, index) in stallList" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </div>
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card class="mt_20" style="border: 1px solid #ccc; border-radius: 5px; padding: 0px" :showTitle="false">
      <mealExpenses ref="mealExpenses" :form.sync="this.form" @validate="validate"></mealExpenses>
    </cus-card>
    <Spin size="large" fix v-if="loading"> </Spin>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
  getboardrate,
  getLabourStrengthList,
  getStallInfo,
  unitInfo,
  judgeIsCrateHandaworkMeal
} from "@/api/business/dishesModule";
import mealExpenses from "../createHandmadeTwo.vue";
export default {
  props: {
    producel: {
      type: Number,
      default: 0
    }
  },
  //import引入的组件需要注入到对象中才能使用
  components: { mealExpenses },
  data() {
    //这里存放数据

    return {
      loading: false,
      unitInfoData: [],
      form: {
        ovenClass: null,
        stallId: null,
        stallDescr: null,
        strength: null,
        startDate: "",
        stopDate: "",
        name: "",
        typeMeal: 0,
        type: 0,
        dateString: "",
        handType: 0, // 0 代表只有三餐的手工食谱 1 代表带间餐夜餐等的手工食谱
        make_type: 0 //0代表智能生成食谱 1代表智能生成食谱
      },
      nameItem: {
        ovenClass: "",
        stall: "",
        name: ""
      },

      ovenClassList: [], // 伙食灶别列表
      labourStrengthList: [], // 劳动强度列表
      stallList: [], // 档口列表
      dateList: [],
      dateStr: "",
      pickerTime: {
        firstDayOfWeek: 1
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化,改变智能食谱或手工食谱
  watch: {
    producel: {
      handler(newVal) {
        this.form.make_type = newVal;
        this.form.strength = this.labourStrengthList[0].labourId;
        console.log("----", this.form.make_type);
        console.log(this.form, 34343);
        this.changeregion();
        // console.log('action Value:', val, this.levelPersonal)
      }
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loading = true;
    this.form.dateString =
      new Date(new Date().toLocaleDateString()).getTime() +
      24 * 60 * 60 * 1000 * 7;
    this.getCurrentWeek(this.form.dateString);
    Promise.all([
      this.getboardrateApi(),
      this.getLabourStrengthListApi(),
      this.unitInfoApi(),
      this.getStallInfoApi(),
    ])
      .then(result => {
        window.parentMounted = this._isMounted;
        if (this.ovenClassList.length) {
          this.$refs["mealExpenses"].form.strength = this.labourStrengthList[0].labourId;
          this.form.ovenClass = this.unitInfoData.boardRateId ? this.unitInfoData.boardRateId : this.ovenClassList[0].id;
          this.$refs["mealExpenses"].onit(this.form.ovenClass);
          console.log(this.$refs["mealExpenses"].form, 999)
          this.nameItem.ovenClass = this.ovenClassList.find((item) => item.id == this.form.ovenClass).ovenClass;
        }
        if (this.stallList.length) {
          this.form.stallId = this.stallList[0].id;
          this.form.stallDescr = this.stallList[0].stallDescr;
          this.nameItem.stall = this.stallList[0].name;
        }
        this.form.strength = this.labourStrengthList[0].labourId;
        console.log('form.strength', this.form, this.form.strength);
        this.form.name = `${this.nameItem.stall +
          this.nameItem.name +
          this.nameItem.ovenClass +
          this.form.startDate}-${this.form.stopDate}号食谱`;
        this.loading = false;
      })
      .catch(e => {
        this.loading = false;
      });
    console.log()
  },
  //方法集合
  methods: {
    validate() {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          this.$refs.mealExpenses.checkDish();
        }
      });
    },
    // 获取单位信息 --接口
    unitInfoApi() {
      return new Promise((resolve, reject) => {
        unitInfo({})
          .then(res => {
            this.form.loading = false;
            if (res.retCode == 2000) {
              this.unitInfoData = res.data[0];
              this.nameItem.name = res.data[0].unitName || "";
              // this.form.ovenClass = res.data[0].boardRateId?res.data[0].boardRateId:this.ovenClassList[0].id;
              // this.$refs["mealExpenses"].form.ovenClass = res.data[0].boardRateId?res.data[0].boardRateId:this.ovenClassList[0].id;
              resolve();
            }
          })
          .catch(err => {
            reject();
          });
      });
    },
    // 获取伙食灶别列表 --接口
    getboardrateApi() {
      return new Promise((resolve, reject) => {
        getboardrate({
          boardRateType: 0
        })
          .then(res => {
            this.form.loading = false;
            if (res.retCode == 2000) {
              this.ovenClassList = res.data;
              // this.$refs["mealExpenses"].form.ovenClass = res.data[0].id;
            }
            resolve();
          })
          .catch(err => {
            reject();
          });
      });
    },
    // 获取劳动强度列表 --接口
    getLabourStrengthListApi() {
      return new Promise((resolve, reject) => {
        getLabourStrengthList({})
          .then(res => {
            this.form.loading = false;
            if (res.retCode == 2000) {
              let arr = [];
              res.data.forEach(item => {
                arr.push({ labourId: item.labourId, strength: item.strength });
                if (item.activityTableList.length) {
                  item.activityTableList.forEach(it => {
                    arr.push({
                      labourId: it.labourId,
                      strength: it.activityName
                    });
                  });
                }
              });
              this.labourStrengthList = arr;
            }
            resolve();
          })
          .catch(err => {
            reject();
          });
      });
    },
    // 获取档口列表 --接口
    getStallInfoApi() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        getStallInfo({})
          .then(res => {
            if (res.retCode == 2000) {
              this.stallList = res.data;
              
              // this.$refs["mealExpenses"].form.ovenClass = this.form.ovenClass;
              // this.$refs["mealExpenses"].onit();
            }
            resolve();
          })
          .catch(err => {
            reject();
          });
      });
    },
    //时间week事件
    weekChange(date) {
      this.getCurrentWeek(date);
      this.form.name = `${this.nameItem.stall +
        this.nameItem.name +
        this.nameItem.ovenClass +
        this.form.startDate}-${this.form.stopDate}号食谱`;
      this.$refs.mealExpenses.onit(this.form.ovenClass);
    },
    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }
      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime =
            nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      this.dateList = [...beforweek, ...afterWeek];
      if (this.dateList.length) {
        this.dateStr = `${this.dateList[0]} - ${this.dateList[this.dateList.length - 1]
          }`;
        this.form.startDate = `${this.dateList[0]}`;
        this.form.stopDate = `${this.dateList[this.dateList.length - 1]}`;
      } else this.dateStr = "";
    },
    changeOvenClass(value) {
      this.nameItem.ovenClass = value.label;
      this.form.name = `${this.nameItem.stall + this.nameItem.name + value.label.trim() + this.form.startDate}-${this.form.stopDate}号食谱`;
        console.log( this.form.name);
      this.$refs.mealExpenses.onit(this.form.ovenClass);
    },
    changeStrength() {
      console.log(this.form.strength);
      this.$refs.mealExpenses.onit(this.form.ovenClass);
    },
    // 改变伙食区域
    changeregion() {
      this.$refs.mealExpenses.onit(this.form.ovenClass);
    },
    changeStall(value) {
      console.log(value, 444)
      this.nameItem.stall = value ? value.label : '';
      console.log('this.nameItem.stall', this.nameItem.stall)
      this.form.name = `${this.nameItem.stall +
        this.nameItem.name +
        this.nameItem.ovenClass +
        this.form.startDate}-${this.form.stopDate}号食谱`;
      let a = this.stallList.filter(item => item.id == value ? value.value : '');
      if (a) {
        this.form.stallDescr = a[0].stallDescr ? a[0].stallDescr : '';
      }
    },
    // 点击创建
    // onAdd(value) {
    //     this.$refs["formValidate"].validate((valid) => {
    //         if (valid) {
    //             this.form.handType = value;
    //             judgeIsCrateHandaworkMeal({
    //                 beginDate: this.form.startDate,
    //                 endDate: this.form.stopDate,
    //                 mealType: 0
    //             }).then((res) => {
    //                 if (res.retCode == 2000) {
    //                     this.$Message.success("允许手工生成本周食谱, 正在前往生成...");
    //                     setTimeout(()=> {
    //                         this.$router.push({
    //                             name:'手工创建食谱',
    //                             query:{
    //                                 form: JSON.stringify(this.form)
    //                             }
    //                         })
    //                     }, 1500)

    //                 }
    //             });
    //         }
    //     });

    // },
    openChoose() {
      this.$refs["chooseMealtimes"].show();
    },
    // 选择餐次回调
    chooseMealsOk(arr) {
      this.form.handTypeArr = this.$cu.deepClone(arr);
      this.onAdd(1);
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() { },

  beforeCreate() { }, //生命周期 - 创建之前
  beforeMount() {
    window.parentMounted = this._isMounted;
  }, //生命周期 - 挂载之前
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() {
    window.parentMounted = this._isMounted;
  }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() { }, //生命周期 - 销毁完成
  activated() { } //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped></style>
